package hard合并K个链表;

import org.testng.annotations.Test;

public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2){
        ListNode prehead = new ListNode(-1);

        ListNode prev = prehead;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                prev.next = l1;
                l1 = l1.next;
            } else {
                prev.next = l2;
                l2 = l2.next;
            }
            prev = prev.next;
        }
        prev.next = l1 == null ? l2 : l1;
        return prehead.next;
    }
    public ListNode mergeKLists(ListNode[] lists) {
        ListNode list = null;
        for (int i = 0; i < lists.length; i++) {
            list = mergeTwoLists(list ,lists[i]);
        }
        return list;
    }
    @Test
    public void test(){
        ListNode l1 = new ListNode(1,new ListNode(4,new ListNode(5,null)));
        ListNode l2 = new ListNode(1,new ListNode(3,new ListNode(4,null)));
        ListNode l3 = new ListNode(2,new ListNode(6,null));
        ListNode[] lists = {l1,l2,l3};
        ListNode lt = mergeKLists(lists);
        while(lt!=null){
            System.out.println(lt.val);
            lt = lt.next;
        }
    }
}
